<?php
namespace Wap\Controller;
use Common\Model\HouseWorkModel;
use Common\Model\MarqueeModel;
use Common\Model\SmsModel;
use Common\Model\UserModel;
use Common\Model\WeixinModel;
use Wap\BaseController;
use Common\Model\EventsModel;
use Common\Model\PointMallModel;
use Common\Model\UtilsModel;
class HouseWorkController extends BaseController {
    //家政首页
    public function index(){
        $uid=session('uid')+0;

        $marqueeList=MarqueeModel::getMarqueeList(MarqueeModel::MARQUEE_HOUSE_INDEX,4,1);
        $this->smarty->assign('marquee',$marqueeList);
        //UserModel::addUserValByAction($uid,OPT_ENTER_EVENT);
        //session('tip',S('tip_'.$uid));
        $this->smarty->assign('userinfo',session());


        $data = HouseWorkModel::getOnlineList(1,8);

        $this->smarty->assign('title',C('SITE_NAME').'-家政服务');
        $this->smarty->assign('data',$data['data']);

        if($this->isWechat) {
            $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
            //微信分享相关
            $this->smarty->assign('isWxShare', true);
            $this->smarty->assign('wxTitle', "丸子妈妈-家政服务");
            $this->smarty->assign('wxDesc',"");
            $this->smarty->assign('wxLink', $protocol.$_SERVER['HTTP_HOST'].U("index"));
            $this->smarty->assign('wxImage', "http://wzma.176dp.cn/Public/Wap/images/logo.jpg");
            $this->smarty->assign('wxObjType',OBJ_TYPE_ACTIVITY);
            $this->smarty->assign('wxObjID',0);
        }

        //是否当日首次签到
        signAssignWap($uid,$this->smarty);

        $this->smarty->display("HouseWork/index.html");
    }

    //加载更多
    public function loadMore(){
        $page = I('get.page',2,'intval');
        $channel = I('get.channel',0,'intval');
        $my = I('get.my',0,'intval');
        $uid=session('uid')+0;
        $data = HouseWorkModel::getOnlineList($page,8);

        $this->smarty->assign('data',$data['data']);
        $html = $this->smarty->fetch('HouseWork/more.html');
        $this->ajaxReturn(array('status'=>0, 'dataHTML'=>$html, 'isPage'=>$data['nextPage']));
    }

    //活动详情
    public function info(){
        $uid=session('uid')+0;
        $id = I("get.id",0,'intval');
        if(!$id) redirect(U('index'));//数据为空返回列表
        $info=HouseWorkModel::getItemInstance()->find($id);
        if($info['status'] != HouseWorkModel::STATUS_ONLINE) redirect(U('index'));//数据为空返回列表

        if($this->isWechat) {
            $domain=UtilsModel::getFullDomain();
            //微信分享相关
            $this->smarty->assign('isWxShare', true);
            $this->smarty->assign('wxTitle', $info['title']);
            $this->smarty->assign('wxDesc',  $info['share_desc']);
            $this->smarty->assign('wxLink', $domain.U('info?id=' . $id . '&fromUid=' . $uid));
            $this->smarty->assign('wxImage', C('UPLOAD_RESOURCE_PREFIX').$info['imgList']);
            $this->smarty->assign('wxObjType',OBJ_TYPE_HOUSEWORK);
            $this->smarty->assign('wxObjID',$id);
        }

        $userinfo=UserModel::getUser($uid);
        if(strlen($userinfo['data']['bindPhone'])<10){
            $this->smarty->assign('noPhone',1);
        }

        $this->smarty->assign('title',$info['title'].'-'.C('SITE_NAME'));//$info['data']['title']
        $this->smarty->assign('info',$info);
        $this->smarty->display("HouseWork/detail.html");
    }


    /**
     * 获取日订单情况
     */
    public function getDailyStatus(){
        $date=I('post.date');
        $itemId=I('get.itemId');

        $date=HouseWorkModel::getIntervalStatus($itemId,$date);
        echo json_encode($date);
        
    }

    //活动报名界面
    public function order(){
        $uid = session('uid');

        //是否当日首次签到
        signAssignWap($uid,$this->smarty);

        $id = I('get.id',0,'intval');

        $data=HouseWorkModel::getItemInstance()->find($id);
        $this->smarty->assign('data',$data);
        $itemStr=explode(';',$data['price']);
        $items=[];
        foreach($itemStr as $item){
            list($name,$price,$unit,$point,$reduce)=explode('/',$item);
            $items[]=[
                'name'=>$name,
                'price'=>$price,
                'unit'=>$unit,
                'point'=>$point,
                'reduce'=>$reduce
            ];
        }
        $this->smarty->assign('items',$items);

        $userinfo=UserModel::getUser($uid);
        if(strlen($userinfo['data']['bindPhone'])<10){
            $this->smarty->assign('noPhone',1);
        }




        $areaName='';
        if ($userinfo['data']['province']>0){
            $region = require WEB_ROOT.'/data/area_info/'.$userinfo['data']['province'].'.php';
            $areaName=$region[$userinfo['data']['province']]['name'];
            if ($userinfo['data']['city']>0){
                $areaName.='/'.$region[$userinfo['data']['city']]['name'];
                if ($userinfo['data']['district']>0){
                    $areaName.='/'.$region[$userinfo['data']['district']]['name'];
                }
            }
        }
        $this->smarty->assign('area',$areaName);
        $this->smarty->assign('address',$userinfo['data']['address']);

        $this->smarty->display("HouseWork/order.html");
    }

    //活动 确定报名
    public function apply(){

        $uid        = session('uid');
        $nickname   = session('nickname');
        $id         = I('post.id',0,'intval');
        
        $data = array('status'=>1, 'msg'=>'参数错误');
        if(!$uid || !$id) $this->ajaxReturn($data);//数据为空返回列表

        $usePoint       = I('post.usePoint',0,'int');
        $area       = I('post.area');
        $address    = I('post.address',null,'strip_tags');
        $mem        = I('post.mem',null,'strip_tags');
        $time       = I('post.time',null,'strip_tags');
        $itemArr    = I('post.item');

        $set=HouseWorkModel::getItemInstance()->find($id);
        if($set['status']!=HouseWorkModel::STATUS_ONLINE){
            $data = array('status'=>1, 'msg'=>'该服务项目已经下架');
            $this->ajaxReturn($data);
        }

        $itemset=explode(';',$set['price']);
        $totalPoint=0;
        $totalFee=0;
        $selected='';
        foreach($itemset as $index=>$one){
            if ($itemArr[$index]<1){
                continue;
            }
            list($name,$price,$unit,$point,$reduce)=explode('/',$one);

            if ($usePoint==1){
                $totalPoint+=$point * $itemArr[$index];
                $totalFee +=($price-$reduce) * $itemArr[$index];
            }else{
                $totalFee +=$price * $itemArr[$index];
            }
            $selected .=$name.' x '.$itemArr[$index]."({$unit})".';';
        }

        $userinfo=UserModel::getInstance()->where('uid='.$uid)->field('point,bindPhone')->find();
        if ($totalPoint>$userinfo['point']){
            $this->ajaxReturn(['status'=>1,'msg'=>'您的扣分不够抵扣本次订单。']);
        }

        list($date,$hour)=explode(' ',$time);
        if (!HouseWorkModel::getTimeOrder($id,$date,$hour)){
            $this->ajaxReturn(['status'=>1,'msg'=>'该时段已经约满了，请选择其它时段。']);
        }

        $new=[];
        $new['itemId']=$id;
        $new['itemName']=$set['title'];
        $new['itemDetail']=$selected;
        $new['price']=$totalFee;
        $new['mem']=$mem;
        $new['area']=$area;
        $new['address']=$address;
        $new['score']=0;
        $new['orderTime']=$time;
        $new['addTime']=time();
        $new['status']=HouseWorkModel::ORDER_STATUS_INIT;
        $new['point']=$totalPoint;



        $new['uid']=$uid;
        $new['phoneNumber']=$userinfo['bindPhone'];
        $new['nickname']=$nickname;

        HouseWorkModel::getItemInstance()->startTrans();
        HouseWorkModel::timeOrderPlus($id,$date,$hour);

        $result = HouseWorkModel::getOrderInstance()->add($new);

        if($result!==false && $totalPoint>0){
                $tempR=UserModel::minusPoint($uid,-1,$totalPoint,OPT_ORDER_HOUSEWORK,"{$result}|{$selected}");
                if ($tempR['status']!=0){
                    HouseWorkModel::timeOrderReduce($id,$date,$hour);
                    HouseWorkModel::getItemInstance()->rollback();
                    $this->ajaxReturn(['status'=>1,'msg'=>'预约失败，请稍后重试，或联系客服']);
                }
                $dataSuccess['ext']=$tempR['ext'];
        }

        if ($result!==false){
            HouseWorkModel::getItemInstance()->commit();
            session('houseWorkOrderId',$result);
            HouseWorkModel::sendTemplateMsg($result,$set['title'],$totalFee);


            $param = [
                'user' =>$nickname,
                'phone' =>$userinfo['bindPhone'],
                'address' =>$address,
                'item'  =>  $new['itemName'],
                'money' => $new['price'],
                'time'  => $new['orderTime']
            ];
            if (defined('HOUSEWORK_NOTIFY_PHONE') && defined('HOUSEWORK_NOTIFY_SMSTPL')) {
                preg_match_all('/\d{11}/',HOUSEWORK_NOTIFY_PHONE,$phones);
                foreach ($phones[0] as $phone) {
                    SmsModel::sendSms($phone, HOUSEWORK_NOTIFY_SMSTPL, $param);
                }

            }
            $this->ajaxReturn(['status'=>0,'msg'=>'预约成功']);
        }
        HouseWorkModel::timeOrderReduce($id,$date,$hour);
        HouseWorkModel::getItemInstance()->rollback();
        $this->ajaxReturn(['status'=>1,'msg'=>'预约失败，请稍后重试，或联系客服']);

    }


    public function success(){
        $orderId=session('houseWorkOrderId');
        $orderInfo=HouseWorkModel::getOrderInstance()->find($orderId);
        $itemId=$orderInfo['itemId'];
        $itemInfo=HouseWorkModel::getItemInstance()->find($itemId);
        $this->smarty->assign('order',$orderInfo);
        $this->smarty->assign('item',$itemInfo);
        $this->smarty->display("HouseWork/result.html");
    }


    public function orderList(){



        $uid = session('uid');
        $mReturn=HouseWorkModel::getOrderList($uid,1,C('LIST_PAGE_SIZE'));
        $this->smarty->assign('list',$mReturn['data']);
        $this->smarty->assign('IS_COMPLETE',HouseWorkModel::ORDER_STATUS_COMPLETE);
        $this->smarty->display("HouseWork/orderList.html");
    }


    public function orderListMore(){
        $p=I('post.p',2,'int');
        //用户uid 从session里获取
        $uid = session('uid');
        $mReturn=HouseWorkModel::getOrderList($uid,$p,C('LIST_PAGE_SIZE'));
        $this->smarty->assign('list',$mReturn['data']);
        $this->smarty->assign('IS_COMPLETE',HouseWorkModel::ORDER_STATUS_COMPLETE);
        $html=$this->smarty->fetch('HouseWork/orderListItem.html');
        $this->ajaxReturn(array('status'=>0, 'dataHTML'=>$html, 'isPage'=>$mReturn['nextPage']));

    }


    public function comment(){
        $orderId=I('post.orderId',0,'int');
        $con=I('post.con','');
        $score=I('post.score',0);
        $con=urldecode($con);

        $order=HouseWorkModel::getOrderInstance()->find($orderId);

        $uid = session('uid');
        if (!$order||$order['uid']!==$uid){
            $this->ajaxReturn(['status'=>1,'msg'=>'指定订单错误']) ;
        }
        if ($order['status']!=HouseWorkModel::ORDER_STATUS_COMPLETE){
            $this->ajaxReturn(['status'=>1,'msg'=>'只有结束的订单才可评价']) ;
        }
        HouseWorkModel::getOrderInstance()->where("id={$orderId}")->setField(['comment'=>$con,'score'=>$score]);
        $this->ajaxReturn(['status'=>0,'msg'=>'评价成功']) ;
    }




}